package com.iqilu.ksd.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.tedcoder.wkvideoplayer.constant.VideoType;
import com.android.tedcoder.wkvideoplayer.model.Video;
import com.android.tedcoder.wkvideoplayer.model.VideoUrl;
import com.android.tedcoder.wkvideoplayer.view.MediaController;
import com.android.tedcoder.wkvideoplayer.view.SuperVideoPlayer;
import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.VideoDetailAdapter;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.bean.VideoDetailBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.SharePlatform;
import com.iqilu.ksd.event.StopPlayRadioEvent;
import com.iqilu.ksd.event.StopPlayVideoEvent;
import com.iqilu.ksd.utils.ConvertUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.NetworkUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.iqilu.ksd.utils.ShareUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import okhttp3.Call;
import okhttp3.Request;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/12/31.
 */

public class VideoDetailActivity extends BaseActivity implements View.OnClickListener {

    private UserBean user;
    private int page;
    private int catid;
    private VideoDetailBean data;
    private ArrayList<VideoDetailBean> list;
    private VideoDetailAdapter adapter;
    private boolean firstLoad = true;

    private LigDialog ligDialog;

    private SimpleDraweeView bgPlayer;
    private ImageView btPlay;
    private SuperVideoPlayer superVideoPlayer;
    private TextView tvTitle;
    private TextView tvDate;
    private TextView tvCatname;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private RelativeLayout layLoading;
    private ImageView btBack;
    private ImageView btLove;
    private RelativeLayout layTitle;
    private LinearLayout layFooter;
    private LinearLayout layComment;
    private TextView tvComment;
    private LinearLayout layLike;
    private TextView tvLike;
    private ImageView imgLike;
    private ImageView btShare;

    private int mWidth;
    private int mHeight;
    private int screenHeight;

    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        @Override
        public void onCloseVideo() {
        }

        @Override
        public void onSwitchPageType() {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                superVideoPlayer.setPageType(MediaController.PageType.SHRINK);
                toggleHide(false);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                superVideoPlayer.setPageType(MediaController.PageType.EXPAND);
                toggleHide(true);
            }
        }

        @Override
        public void onPlayFinish() {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videodetail);
        ShareSDK.initSDK(this);
        user = ((MyApplication) getApplication()).getUser();
        initView();
        superVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);
        mWidth = ScreenUtils.getScreenWidth(this);
        screenHeight = ScreenUtils.getScreenHeight(this);
        mHeight = ConvertUtils.dp2px(this, 250);

        catid = getIntent().getIntExtra("catid", 0);

        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        adapter = new VideoDetailAdapter(this);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        adapter.setOnItemClickListener(new VideoDetailAdapter.OnItemClickListener() {
            @Override
            public void OnItemClickListener(View view, int position) {
                data = list.get(position);
                getContent();
            }
        });
        rvList.setAdapter(adapter);
        page = 1;
        getList();
    }

    private void initView() {
        bgPlayer = getView(R.id.bg_player);
        btPlay = getView(R.id.bt_play);
        superVideoPlayer = getView(R.id.superVideoPlayer);
        tvTitle = getView(R.id.tv_title);
        tvDate = getView(R.id.tv_date);
        tvCatname = getView(R.id.tv_catname);
        layTitle = getView(R.id.lay_title);
        layFooter = getView(R.id.lay_footer);
        xRefreshView = getView(R.id.xRefreshView);
        rvList = getView(R.id.rv_list);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        rvList.setHasFixedSize(true);
        layLoading = getView(R.id.lay_loading);
        layFooter = getView(R.id.lay_footer);
        btBack = getView(R.id.bt_back);
        btLove = getView(R.id.bt_love);
        btLove.setVisibility(View.INVISIBLE);
        layComment = getView(R.id.lay_comment);
        tvComment = getView(R.id.tv_comment);
        layLike = getView(R.id.lay_like);
        tvLike = getView(R.id.tv_like);
        imgLike = getView(R.id.img_like);
        btShare = getView(R.id.bt_share);

        layFooter.setOnClickListener(this);
        btBack.setOnClickListener(this);
        layComment.setOnClickListener(this);
        layLike.setOnClickListener(this);
        btShare.setOnClickListener(this);
        btPlay.setOnClickListener(this);
    }

    private void initBottom() {
        tvTitle.setText("" + data.getTitle());
        tvDate.setText("" + data.getDate());
        tvCatname.setText(Uri.decode(data.getCatname()));
        tvComment.setText("" + data.getCommentnum());
        tvLike.setText("" + data.getLikenum());
        if (data.getLiked() == 1) {
            imgLike.setImageResource(R.drawable.bt_like_orange);
        }
    }

    private void toPlay() {
        if (NetworkUtils.isAvailable(this) && !NetworkUtils.isWifiConnected(this)) {
            showSelectDialog();
        } else {
            startPlay();
        }
    }

    private void showSelectDialog() {
        final MaterialDialog dialog = new MaterialDialog(this);
        dialog.content(getString(R.string.not_wifi))
                .btnText(getString(R.string.cancel), getString(R.string.continue_play))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        startPlay();
                        dialog.dismiss();
                    }
                }
        );
    }

    public void startPlay() {
        if (data == null) return;
        btPlay.setVisibility(View.GONE);
        superVideoPlayer.setVisibility(View.VISIBLE);
        superVideoPlayer.setAutoHideController(true);
        superVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);
        Video video = new Video();
        VideoUrl videoUrl = new VideoUrl();
        videoUrl.setFormatName("480P");
        videoUrl.setFormatUrl(data.getFileurl());
        ArrayList<VideoUrl> arrayList1 = new ArrayList<>();
        arrayList1.add(videoUrl);
        video.setVideoName(data.getTitle());
        video.setVideoUrl(arrayList1);
        video.setmVideoType(VideoType.VIDEO_ONLINE);
        ArrayList<Video> videoArrayList = new ArrayList<>();
        videoArrayList.add(video);
        superVideoPlayer.loadMultipleVideo2(videoArrayList, 0, 0, 0);
        firstLoad = false;
        EventBus.getDefault().post(new StopPlayVideoEvent());
        EventBus.getDefault().post(new StopPlayRadioEvent());
    }

    /***
     * 恢复屏幕至竖屏
     */
    private void resetPageToPortrait() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            superVideoPlayer.setPageType(MediaController.PageType.SHRINK);
            toggleHide(false);
        }
    }

    /***
     * 旋转屏幕之后回调
     *
     * @param newConfig newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (null == superVideoPlayer) return;
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().invalidate();
            superVideoPlayer.getLayoutParams().height = mWidth;
            superVideoPlayer.getLayoutParams().width = screenHeight;
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            superVideoPlayer.getLayoutParams().height = mHeight;
            superVideoPlayer.getLayoutParams().width = mWidth;
        }
    }

    private void toggleHide(boolean hide) {
        int status;
        if (hide) {
            status = View.GONE;
        } else {
            status = View.VISIBLE;
        }
        layTitle.setVisibility(status);
        xRefreshView.setVisibility(status);
        layFooter.setVisibility(status);
    }

    private void toComment() {
        Intent intent = new Intent(this, CommentActivity.class);
        intent.putExtra("articleid", data.getId());
        intent.putExtra("catid", data.getCatid());
        intent.putExtra("type", "video");
        startActivity(intent);
    }

    private void toShare() {
        if (data == null) return;
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(data.getTitle());
        sp.setTitleUrl(data.getShareurl());
        sp.setText(data.getDescription());
        sp.setSiteUrl(data.getShareurl());
        sp.setUrl(data.getShareurl());
        sp.setImageUrl(data.getThumb());
        sp.setSite(getString(R.string.app_name));
        ShareUtils.getInstance().setShareParams(this, sp).show();
    }

    void toLike() {
        if (user == null || user.getId() == 0) {
            Toast.makeText(this, R.string.not_login, Toast.LENGTH_SHORT).show();
            return;
        }
        if (data.getLiked() != 1) {
            addLike();
        } else {
            delLike();
        }
    }

    // 点赞
    private void addLike() {
        String url = Api.URL_ARTICLE_LIKE + "?id=" + data.getId() + "&catid=" + data.getCatid() + "&type=video";
        String query = "id=" + data.getId() + "&catid=" + data.getCatid() + "&type=video";
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(query)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(VideoDetailActivity.this, R.string.like_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            Toast.makeText(VideoDetailActivity.this, R.string.like_add_success, Toast.LENGTH_SHORT).show();
                            imgLike.setImageResource(R.drawable.bt_like_orange);
                            int count = Integer.valueOf("" + tvLike.getText()) + 1;
                            tvLike.setText("" + count);
                            data.setLiked(1);
                        } else {
                            Toast.makeText(VideoDetailActivity.this, R.string.like_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    // 取消点赞
    private void delLike() {
        String url = Api.URL_ARTICLE_LIKE + "?id=" + data.getId() + "&catid=" + data.getCatid() + "&type=video";
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(VideoDetailActivity.this, R.string.like_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    Toast.makeText(VideoDetailActivity.this, R.string.like_del_success, Toast.LENGTH_SHORT).show();
                    imgLike.setImageResource(R.drawable.bt_like);
                    int count = Integer.valueOf("" + tvLike.getText()) - 1;
                    count = Math.max(0, count);
                    tvLike.setText("" + count);
                    data.setLiked(0);
                } else {
                    Toast.makeText(VideoDetailActivity.this, R.string.like_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    private void getList() {
        String url = Api.URL_VIDEO_LIST + "?catid=" + catid + "&page=" + page;
        Log.i("ttt", "url=" + url);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                afterRequest();
                layLoading.setVisibility(View.VISIBLE);
                Toast.makeText(VideoDetailActivity.this, R.string.load_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                afterRequest();
                ArrayList<VideoDetailBean> result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<VideoDetailBean>>() {
                });
                if (page == 1) {
                    if (result == null || result.size() == 0) {
                        layLoading.setVisibility(View.VISIBLE);
                        Toast.makeText(VideoDetailActivity.this, R.string.load_error, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    list = result;
                    adapter.setData(list);
                    if (firstLoad) {
                        data = list.get(0);
                        getContent();
                    }
                } else {
                    if (result == null || result.size() == 0) {
                        Toast.makeText(VideoDetailActivity.this, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (list == null) {
                        return;
                    }
                    list.addAll(result);
                    adapter.setData(list);
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void getContent() {
        String url = Api.URL_VIDEO + "?id=" + data.getId() + "&catid=" + data.getCatid();
        Log.i("ttt", "url=" + url);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(VideoDetailActivity.this, getString(R.string.waiting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
                Toast.makeText(VideoDetailActivity.this, R.string.load_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                data = JSONUtils.requestDetail(response, "data", VideoDetailBean.class);
                if (data != null) {
                    bgPlayer.setImageURI(Uri.parse(data.getThumb()));
                    initBottom();
                    if (!firstLoad) {
                        toPlay();
                    }
                } else {
                    Toast.makeText(VideoDetailActivity.this, R.string.load_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void afterRequest() {
        layLoading.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.lay_comment:
                toComment();
                break;
            case R.id.lay_like:
                toLike();
                break;
            case R.id.bt_share:
                toShare();
                break;
            case R.id.bt_play:
                toPlay();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            resetPageToPortrait();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
